﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Codematic.test
{
    public partial class ProcessForm1 : Form
    {
        int MaxCOunt = 0;
        int CurrentNum = 0;

        public ProcessForm1()
        {
          
            InitializeComponent();


            backgroundWorker1.WorkerSupportsCancellation = true; // 设置可以取消
            backgroundWorker1.WorkerReportsProgress = true; // 设置可以取消

            backgroundWorker1.DoWork += new DoWorkEventHandler(DoWork);
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);


        }

        private void button1_Click(object sender, EventArgs e)
        {
            MaxCOunt = 3;
            backgroundWorker1.RunWorkerAsync();


        }
        void DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;

            if (bw.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                Handle(MaxCOunt);
            }
        }
        void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Error");
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("取消了啊");
            }
            else
            {
                MessageBox.Show("Completed");
            }

        }


        void UpdateProgress(object sender, ProgressChangedEventArgs e)
        {
            int progress = e.ProgressPercentage;
            progressBar1.Value = progress;
            label1.Text = CurrentNum .ToString()+ "/" + MaxCOunt.ToString();

            

        }

        /// 10 秒相应事件
        public void Handle(int maxCount)
        {
            backgroundWorker1.ReportProgress(0);
            
            for (int i = 0; i < maxCount; i++)
            {
             
                Random ra = new Random();
                int j = ra.Next(1, 5);
                Thread.Sleep(j * 1000);

                CurrentNum = (i + 1);
                backgroundWorker1.ReportProgress((i+1) * 100 / maxCount);

            }


        }

        private void button3_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
        }


    }
}
